<?php
/**
 * Created by PhpStorm.
 * User: Qch
 * Date: 2016/10/30
 * Time: 14:07
 */

namespace Application\System\Controller\X;


use Aoe\Emulator\Ifc\Key;
use Aoe\Emulator\Ifc\Type;
use Aoe\Emulator\Schema\Element\Element;
use Aoe\Emulator\Schema\Element\Relation;
use Aoe\Emulator\Schema\Model;
use Aoe\Emulator\Schema\Models;
use Throwable;

/**
 * # 将Schema定义转换为中间码
 */
class Standard
{
    /**
     *
     * @param Models $schema
     * @param bool   $install
     *
     * @return array<array{
     *             name: string,
     *             label: string,
     *             comment?: string,
     *             elements: array{
     *                 name: string,
     *                 label: string,
     *                 pascal: string,
     *                 must: bool,
     *                 nullable: bool,
     *                 default?: mixed,
     *                 comment?: string,
     *                 length?: int,
     *                 double?: bool,
     *                 unsigned?: bool
     *         }>
     */
    public static function sql(Models $schema, bool $install = true): array
    {
        $tables = [];
        
        foreach ($schema->getIterator() as $model) {
            // 非数据库存储格式
            /** @var Model $model */
            if ($model->isExtend() || $model->useJson()) continue;
            
            $tables[] = self::_table_sql($model, $install);
        }
        
        return $tables;
    }
    
    /**
     * 创建表模式
     *
     * @param Model $model
     * @param bool  $install
     *
     * @return array
     */
    private static function _table_sql(Model $model, bool $install = true): array
    {
        if (!$install) return [Key::NAME => $model->getTableName()];

        $columns = [];
        /** @var Element $element */
        foreach ($model->getElements()->getIterator() as $element) $columns[] = self::_column_sql($element);

        return [
            Key::NAME     => $model->getTableName(),
            Key::LABEL    => $model->label,
            'comment'     => $model->get('comment'),
            Key::ELEMENTS => $columns,
        ];
    }

    private static function _column_sql(Element $element)
    {
        $column            = $element->get();
        $column[Key::NAME] = $element->getColumn();

        if ($element->isRelation()) {
            try {
                /** @var Relation $element */
                $column[Type::UUID] = $element->getRelateModel()->isUuid();
            }catch (Throwable) {}
        }

        return $column;
    }
}